const express = require('express');
const multer  = require('multer');
const path = require('path');
const formatData = require('../utils/tool');
const mongo = require('../utils/mongo');
const { send } = require('process');
const router = express.Router();

// 1.1 配置multer中间件的上传参数
let storage = multer.diskStorage({
    // diskStorage：存储在硬盘上的参数

    // 2.上传文件保存目录，无则自动创建，地址的设置是基于输入命令行指令运行的目录
    destination:path.join(__dirname,'../dist/uploads/'),

    // 3.格式化文件名
    filename: function (req, file, cb) {
        // 获取文件后缀名
        let ext = path.extname(file.originalname);

        cb(null, file.fieldname + '-' + Date.now() + ext);
    }
})
// 1.2 设置中间件
let uploadMiddleware = multer({storage});


// 2.更新头像
router.post('/avatar',uploadMiddleware.single('avatar'),(req,res)=>{
    // 2.1 获取信息
    let {id} = req.body;
    let picFile = req.file;

    // 2.2 更新用户信息
    let avatarUrl = '/uploads/'+picFile.filename;
    try{
        const result = mongo.update('user',{_id:id},{$set:{avatarUrl}})
        res.send(formatData({data:{_id:id,avatarUrl}}))
    }catch(err){
        res.send(formatData({code:0}))
    }
})

module.exports = router;